/**   
* @Title: BindLoginContoller.java 
* @Package com.leesche.zcsp.node.web.controller.wechat.bind.login 
* @Description:() 
* @author dennies yang
* @date 2016年10月20日 下午3:04:25 
* @version V1.0   
*/
package com.leesche.zcsp.node.web.controller.wechat.bind;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysModuleCondition;
import com.leesche.zcsp.node.web.vo.Principal;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.leesche.zcsp.node.pay.wecha.data.Message;
import com.leesche.zcsp.node.pay.wecha.data.Oauth2To;
import com.leesche.zcsp.node.pay.wecha.service.WechatService;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.controller.template.LoginTemplate;
import com.leesche.zcsp.node.web.model.SysUser;
import com.leesche.zcsp.node.web.service.SysUserService;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.SysUserDto;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.Account;

/**   
* @Title: BindLoginContoller.java 
* @Package com.leesche.zcsp.node.web.controller.wechat.bind.login 
* @Description:() 
* @author dennies yang
* @date 2016年10月20日 下午3:04:25 
* @version V1.0   
*/
@Controller
@RequestMapping(value = "/wechat/bind/login")
public class BindLoginContoller extends LoginTemplate {
    private static final Logger logger = Logger.getLogger(BindLoginContoller.class);
    
    @Autowired
	PrivilegeService privilegeService;
    
	@Autowired
	WechatService wechatService;	
	@Autowired 
	SysUserService sysUserService;
	
	private final static String LOGIN_MAINVIEW = "wechat/bind/login/mainView";
	
	//重定向地址
	private final static String AUTHORIZATION_VIEW = "/wechat/bind/bind/showView";
	private final static String AUTHORIZATION_MAIN = "/wechat/bind/login/main";

	/**
	 * 
	* @Title: m 
	* @Description: TODO(通过微信授权界面获取用户的openid,通过openid判断当前账号是否存在) 
	* @param @param model
	* @param @return   
	* @return String   
	* @throws
	 */
	@RequestMapping(value = "main", method = RequestMethod.GET)
    public String main(String code,Model model, HttpServletRequest request, HttpServletResponse response){
		//获取Openid
		if(StringUtils.isBlank(code)){
			return LOGIN_MAINVIEW;
		}
		Message<Oauth2To> message = wechatService.getOauth(code);
		//Oauth2To oauth2To=new Oauth2To();
    	//oauth2To.setOpenid("o616as_W_4LV14_zXUoQkZjmhEk4");
        //Message<Oauth2To> message = Message.success(oauth2To, null);
		
		if(Message.isSuccess(message.getType())){
			Cookie cookie = new Cookie("openid", message.getContent().getOpenid());
            cookie.setMaxAge(60 * 60);
            cookie.setPath("/");
            response.addCookie(cookie);
			System.out.println("OpenID="+message.getContent().getOpenid());
			logger.info("OpenID="+message.getContent().getOpenid());
			QuerySysUserCondition conditon = new QuerySysUserCondition();
			conditon.setOpenid(message.getContent().getOpenid());
			SysUserDto loginUser = sysUserService.findByCondition(conditon);
			if(loginUser!=null){//跳转绑定界面
				String principalName = loginUser.getBusinessno() != null ? loginUser
						.getBusinessno() : loginUser.getUsername();

				Principal principal = new Principal(loginUser.getUserid(),
						loginUser.getPuserid(), principalName,
						loginUser.getBusinessno(), loginUser.getNtype(),
						loginUser.getOpenid(), Constants.MODULE_TYPE_WECHAT,loginUser.getShortcode());

				QuerySysModuleCondition querySysModuleCondition = new QuerySysModuleCondition();
				querySysModuleCondition.setnType(Constants.MODULE_TYPE_WECHAT);
				querySysModuleCondition.setUserId(principal.getUserid());
				principal.setModuleIds(sysModuleService
						.findModuleIDbyUserID(querySysModuleCondition));

				request.getSession().setAttribute(Constants.LOGIN_CURRENT_USER,
						principal);
				return "redirect:"+AUTHORIZATION_VIEW;
			}
			
		}
        return LOGIN_MAINVIEW;
    }
	
	
	
	/***
	 * 
	* @Title: listView 
	* @Description: TODO(网页授权机制) 
	* @param @param model
	* @param @return   
	* @return String   
	* @throws
	 */
	@RequestMapping(value = "showView", method = RequestMethod.GET)
    public String showView(HttpServletRequest request,Model model){
		//网页授权跳转界面
		StringBuffer url = new StringBuffer();
		url.append(request.getScheme());
		url.append("://");
		url.append(request.getServerName());
		url.append("/"+Constants.SITE_NAME+AUTHORIZATION_MAIN);
		//System.out.println(wechatService.getWechatRedirectUrl(url.toString()));
		return "redirect:" + wechatService.getWechatRedirectUrl(url.toString());
	//	return LOGIN_MAINVIEW;
    }
	
	/***
	 * 
	* @Title: login 
	* @Description: TODO(登录验证) 
	* @param @param session
	* @param @param accout
	* @param @return   
	* @return Map<String,Object>   
	* @throws
	 */
    @ResponseBody
    @RequestMapping(value = "signin", method = RequestMethod.POST)
    public Map<String, Object> login(HttpSession session, Account accout) {
        try {
            return super.userLogin(accout, Constants.MODULE_TYPE_WECHAT);
        } catch (Exception e) {
			logger.error(e.getMessage(),e);
            return WebResult.failure(e).toMap();
        }

    }

}
